<template>
	<view class="main" :style="{ 'background-image': `url(${bg})` }">
		<tanChuang :Visible="isVisible" @isVisibles="isVisibles" />
		<!-- 这个注释是一个弹窗,如今后要加弹窗,直接解开 -->
		<!-- 	<submitVue :Visible="isModalVisible" :selectedAnswers="selectedAnswers" :totalScore="totalScore"
			@isModal="isModal" /> -->

		<view class="title">
			<view class="bg" :class="title != '' ? 'bg-color' : ''">

				<u-icon @click="goBack" size="32" name="arrow-left"></u-icon>
				<text>{{title}}</text>
				<view class="">
				</view>
			</view>

		</view>

		<view class="">

			<view class="container">
				<!-- 进度条 -->
				<view class="schedule">
					<view class="schedule-text">
						当前进度
					</view>
					<view class="progress-bar">
						<view class="progress" :style="{ width: progressWidth + '%' }"></view>
					</view>
					<view class="schedule-num">
						<text class="num">{{ currentQuestionIndex + 1 }}</text>/{{ questions.length }}
					</view>
				</view>

				<!-- 题目和选项 -->
				<view class="question">
					<view class="question-title" >
						<image :src="titBg" mode=""></image>
						{{ currentQuestion.title }}
					</view>

					<view class="question-body">
						<view v-for="(option, index) in currentQuestion.topic" :key="index" class="option">
							<view class="single-option"
								:style="{ 'background-image': option.off ? `url(${textBg})` : 'none' }"
								:class="{ selected: option.off }" @click="selectAnswer(index)">
								{{ getOptionLabel(index) }}. {{ option.title }}
							</view>
						</view>
					</view>


				</view>

			</view>


		</view>
		<!-- 下一题按钮 -->
		<view class="button-box">
			<view v-if="(currentQuestionIndex + 1)>1" class="prev-btn" @click="goToPrevious"
				:disabled="currentQuestionIndex === 0">上一题</view>

			<view class="next-btn" v-if="(currentQuestionIndex + 1)==questions.length"
				 @click="goSubmit">提交</view>
			<view class="next-btn" v-else :class="{'next-btns': (currentQuestionIndex + 1)==1}" @click="goToNext"
				:disabled="!isAnswered">下一题</view>
		</view>


	</view>
</template>

<script>
	import {
		getquestionOne,
		setquestionOne,
		getquestionnaireAnswer
	} from '../../service/api.js'
	import config from "../../utils/config";
	import submitVue from "../../components/submit.vue";
	import tanChuang from "../../components/tanChuang.vue";
	tanChuang
	import {
		toast,
		getStore,
		setStore,
		removeStore
	} from "@/utils/index";
	export default {
		components: {

			submitVue,
			tanChuang
		},
		onShareAppMessage(res) {
			return {
				title: '', // 分享的标题
				path: '/outpatient/survey/index', // 分享的页面路径
				imageUrl: '' // 分享的图片路径
			};
		},
		onLoad(options) {

			if (options.id) {
				this.photoUrl = options.photoUrl;
				this.question.questionnaireId = options.id
				this.getquestion(options.id);
			}

		},
		data() {
			return {
				url: config.host,
				isModalVisible: false,
				isVisible: false,
				totalScore: 0, // 总分数
				bg: config.ossHost + '2024/12/29/2fec091445464cb39d13f3ed1ffef119.png',
				textBg: config.ossHost + '2025/01/02/239248ccbed645e1a4321424cbb1d9ff.png',
                 titBg: config.ossHost + '2025/01/02/1117162523754c00b8ac36409f53e5d5.png',
				result: [{
					"title": "暂缓行动，先调体质",
					"score": "24",
					"hint": "您现阶段对减肥的认知较为薄弱，且可能身体状态并不适合立即进行减肥，建议先通过中医调理体质，如改善便秘、增强脾胃功能等亚健康，待身体状态稳定后再考虑减肥计划，健康是减肥的前提，切勿急于求成。"
				}, {
					"title": "加倍努力",
					"score": "40",
					"hint": "您在减肥方面的认知还需进一步强化，通过提高治疗次数，和医生相互配合，充分认识减肥的重要性与科学性，您的减肥之路将不再艰难，但需注意避免盲目跟风，否则失败率极高。"
				}, {
					"title": "预祝成功",
					"score": "60",
					"hint": "您对减肥有一定的了解，但仍有提升空间，通过深入沟通、调整减肥方案，并结合中医减肥的理念，如平衡阴阳、调和气血，您的减肥之路将更加顺畅，成功机会大增。"
				}, {
					"title": "恭喜您",
					"score": "100",
					"hint": "您已经具备了较高的减肥认知与实践基础，结合中医减肥的疗法，如调理脾胃、疏通经络，您的减肥成功比例极高，期待您健康美丽的蜕变。"
				}],
				questions: [],
				currentQuestionIndex: 0, // 当前问题的索引
				selectedAnswer: null, // 单选题的选中答案
				selectedAnswers: [],
				isAnswered: false, // 是否答题
				title: "减肥心理测试问卷",
				question: {
					memberId: "",
					questionnaireId: "",
					answer: '',
				},
				photoUrl: "",
			};
		},
		computed: {
			resultTitle() {
				const score = this.totalScore;
				// 通过 find 查找第一个符合条件的 result
				const result = this.result.find(item => score >= parseInt(item.score) && (this.result.indexOf(item) + 1 ===
					this.result.length || score < parseInt(this.result[this.result.indexOf(item) + 1].score)));
				return result ? result.title : "暂缓行动，先调体质";
			},
			currentQuestion() {
				return this.questions[this.currentQuestionIndex];
			},
			progressWidth() {
				return (this.currentQuestionIndex + 1) / this.questions.length * 100;
			},

		},
		
		methods: {
			// 获取问题及结果
			async getquestion(id) {
				try {
					let res = await getquestionOne(id);
					if (res.code === 200) {
						this.questions = JSON.parse(res.data.topic);
						this.result = JSON.parse(res.data.results);
						this.title = res.data.title
					} else {
						console.error("获取问题失败", res.message);
					}
				} catch (error) {
					console.error("请求出错", error);
				}
			},
			// 根据总分数获取提示信息
			getHint() {
				const filtered = this.result.filter(item => parseInt(item.score) >= this.totalScore);
				return filtered.length > 0 ? filtered[0].hint : '暂无提示信息';
			},


			goBack() {
				this.isVisible = true;
				// const pages = getCurrentPages();
				// console.log(pages.length, "444444")
				// if (pages.length === 1) {
				// 	// 用户在第一页时，执行自定义逻辑
				// 	uni.navigateTo({
				// 		url: `/pages/${url}`
				// 	})
				// } else {
				// 	uni.navigateBack({
				// 		delta: 1,
				// 	});
				// }
			},



			isVisibles(item) {
				this.isVisible = item
			},

			isModal(item) {
				this.isModalVisible = item
			},
			// 获取选项的字母
			getOptionLabel(index) {
				const labels = ['A', 'B', 'C', 'D', 'E']; // 定义字母标签
				return labels[index] || ''; // 返回字母标签
			},

			async goSubmit() {

				// 检查当前题目是否已经答过
				if (this.currentQuestion.isAnswered) {
					// 如果还有下一题，跳转到下一题
					if (this.currentQuestionIndex < this.questions.length - 1) {
						this.currentQuestionIndex += 1;
					} else {
						// 处理答题完成
						this.selectedAnswers.push(this.currentQuestion);


						// 准备提交的答题数据
						this.question.answer = JSON.stringify(this.selectedAnswers);
						this.question.memberId = JSON.parse(getStore("info")).id || '';

						// 获取 token
						const token = getStore('token');
						if (!token) {
							uni.showToast({
								title: '未登录，请先登录',
								icon: 'none',
							});
							return;
						}

						try {
							// 发起请求
							const response = await uni.request({
								url: this.url + '/app/questionnaireAnswer', // 请求的 URL
								method: 'POST', // 请求方法
								data: this.question,
								header: {
									"Clientid": 'af80f6d0dc2d2f09587d2bd25e384d84',
									'Authorization': `Bearer ${token}`, // 将 token 放入 Authorization 字段
									'Content-Type': 'application/json', // 设置请求体为 JSON 格式
								}
							});

							// 请求成功后的处理
							if (response.data.code === 200) {
								// 如果提交成功，显示成功提示
								uni.showToast({
									title: '答题完成',
									icon: 'success',
									duration: 2000
								});

								// 跳转到评分页面
								uni.navigateTo({
									url: `/outpatient/score/index?score=${this.totalScore}&resultTitle=${this.resultTitle}&getHint=${this.getHint()}&photoUrl=${this.photoUrl}`
								});

							} else {
								// 如果提交失败，显示失败提示
								uni.showToast({
									title: response.data.message || '提交失败',
									icon: 'none',
									duration: 2000
								});
							}

						} catch (error) {
							console.error('请求失败', error);
							uni.showToast({
								title: '请求失败，请稍后重试',
								icon: 'none',
								duration: 2000
							});
						}
					}
				} else {
					uni.showToast({
						title: '请先选择答案',
						icon: 'none'
					});
				}
			},



			selectAnswer(index) {
				const option = this.currentQuestion.topic[index];

				// 切换选项的选中状态
				option.off = !option.off;

				// 确保只允许一个选项被选中
				if (option.off) {
					// 将其他选项的 off 状态设置为 false
					this.currentQuestion.topic.forEach((otherOption, i) => {
						if (i !== index) otherOption.off = false;
					});
				}

				// 清除之前的分数
				let previousScore = this.currentQuestion.selectedAnswer ? this.currentQuestion.selectedAnswer : 0;
				this.totalScore -= previousScore; // 从总分中减去之前的分数

				// 记录当前问题的选中答案（只有一个选项的 off 状态为 true）
				this.currentQuestion.selectedAnswer = option.off ? option.score : null;

				// 如果选项被选中，则加上选项的分数
				if (option.off) {
					this.totalScore += Number(option.score);
				}

				// 设置当前题目的答题完成标记
				this.currentQuestion.isAnswered = this.currentQuestion.selectedAnswer !== null;


			},

			goToNext() {

				this.selectedAnswers.push(this.currentQuestion)
				// 检查当前题目是否已经答过
				if (this.currentQuestion.isAnswered) {
					if (this.currentQuestionIndex < this.questions.length - 1) {
						this.currentQuestionIndex += 1;
					} else {
						uni.showToast({
							title: '答题完成',
							icon: 'success'
						});
					}
				} else {
					uni.showToast({
						title: '请先选择答案',
						icon: 'none'
					});
				}
			},

			goToPrevious() {

				if (this.currentQuestionIndex > 0) {
					this.currentQuestionIndex -= 1;
				}

				// 返回上一题时，更新是否已回答的状态
				const prevQuestion = this.questions[this.currentQuestionIndex];
				this.currentQuestion.isAnswered = prevQuestion.selectedAnswer !== null; // 如果上一题有选中答案，则标记为已答

				this.selectedAnswers.pop()


			}


		}

	}
</script>

<style lang="scss" scoped>
	.main {
		width: 100%;
		height: 100vh;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		padding: 0;
		margin: 0;

	}


	.container {
		padding: 24rpx;
	}

	.progress-bar {
		width: 100%;
		height: 10rpx;
		background: rgba(0, 0, 0, 0.1);
		border-radius: 5px;

	}

	.progress {
		height: 100%;
		background-color: #1A1A1A;
		border-radius: 16rpx;
	}

	.question {
		margin-top: 40rpx;
		padding: 24rpx 24rpx 1rpx 24rpx;
		background: #fff;
		border-radius: 16rpx;
	}

	.question-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
		display: flex;
		align-items: center;
		image{
			width: 6rpx;
			height: 48rpx;
			margin-right: 10rpx;
		}
	}

	.question-body {
		margin-bottom: 20px;
	}

	.option {
		margin-bottom: 24rpx;
	}

	.single-option {
		padding: 0 24rpx;
		line-height: 80rpx;
		color: #4D4D4D;
		font-size: 24rpx;
		height: 80rpx;
		background: #F5F3F0;
		border-radius: 4rpx;
		cursor: pointer;
		box-sizing: border-box;
	}

	.single-option.selected {
		font-weight: bold;

		color: #1A1A1A;
		height: 80rpx;
		width: 100%;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		
		border-radius: 4rpx 4rpx 4rpx 4rpx;
		// border: 2rpx solid #CCA566;
	}

	.single-option:hover {}

	.single-option:disabled {
		background-color: #d3d3d3;
		color: #aaa;
		cursor: not-allowed;
	}

	.button-box {
		position: fixed;
		width: calc(100vw - 48rpx);
		bottom: 50rpx;
		display: flex;
		justify-content: space-between;
		margin: 0 24rpx;

		view {
			height: 82rpx;
			text-align: center;
			line-height: 82rpx;
			border-radius: 56rpx 56rpx 56rpx 56rpx;
		}
	}


	.prev-btn {
		background: #fff;
		color: #CCA566;
		width: 35%;
		margin-right: 5%;
		// background-color: #ccc;
	}

	.next-btn {
		width: 60%;
		background-color: #CCA566;
		font-weight: 400;
		font-size: 32rpx;
		color: #FFFFFF;
	}

	.next-btns {
		width: 100%;

	}

	button:disabled {
		background-color: #ddd;
		cursor: not-allowed;
	}

	.schedule {
		display: flex;
		align-items: center;
		color: #1A1A1A;

		.schedule-text {
			width: 210rpx;
			margin-right: 16rpx;
		}

		.schedule-num {
			width: 140rpx;
			margin-left: 16rpx;

			.num {
				font-size: 36rpx;
				font-weight: bold;
			}
		}
	}

	.bg {
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 24rpx;
		padding-top: 65rpx;


		.title-img {
			width: 100rpx;
		}

		text {
			display: inline-block;

			color: #1a1a1a;
			font-size: 32rpx;
			font-weight: bold;
		}

		view {
			width: 100rpx;
		}
	}

	.bg-color {
		// background: #fff;
	}
</style>